package com.shwread.android.ui.page.chat.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.telephony.PhoneNumberUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ciko.code.logic.bean.ContactBookInfo;
import com.ciko.code.logic.bean.ContactSuperBean;
import com.netease.nim.demo.session.activity.P2PMessageActivity;
import com.netease.nim.demo.session.activity.TeamMessageActivity;
import com.netease.nimlib.sdk.team.model.Team;
import com.shwread.android.qysw.activity.ChatPersonalInfoActivity;
import com.shwread.android.qysw.activity.ContactsActivity;
import com.shwread.android.qysw10000193.R;
import com.shwread.android.ui.dialog.ContactCallSelectDialog;
import com.shwread.android.ui.widget.CircleImageView;
import com.squareup.picasso.Picasso;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import logic.bean.ContactInfo;
import logic.constants.Const;
import logic.util.Util;
import logic.util.Utils;
import logic.util.logutil.LogUtil;


/**
 * 群分组数据适配器
 *
 * @author Jayden
 */
@SuppressLint ("ResourceAsColor")
public class NewContactGroupAdapter
        extends
        BaseExpandableListAdapter
{

    private final Context                          context;

    private List<ContactSuperBean>                        mGroupData;

    private HashMap<String, List<ContactBookInfo>> mChildData;

    private LayoutInflater                         mInflater;
    private ExpandableListView                     lvContacts;

    private ContactCallSelectDialog                selectNum;

    public NewContactGroupAdapter(Context context, ExpandableListView lvContacts, List<ContactSuperBean> mGroupData, HashMap<String, List<ContactBookInfo>> mChildData) {
        this.context = context;
        this.lvContacts = lvContacts;
        this.mChildData = mChildData;
        this.mGroupData = mGroupData;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getGroupCount() {
        return null != mGroupData ? mGroupData.size() : 0;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        if (null == mChildData || null == mGroupData || mGroupData.size() == 0 || null == mGroupData.get(groupPosition) || null == mChildData.get(mGroupData.get(groupPosition).getName()))
        {
            return 0;
        }
        else
        {
            return mChildData.get(mGroupData.get(groupPosition).getName()).size();
        }
    }

    @Override
    public Object getGroup(int groupPosition) {
        return mGroupData.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        if (null == mChildData || null == mGroupData || mGroupData.size() == 0 || null == mGroupData.get(groupPosition) || null == mChildData.get(mGroupData.get(groupPosition).getName()))
        {
            return null;
        }
        else
        {
            return mChildData.get(mGroupData.get(groupPosition).getName()).get(childPosition);
        }
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        View v;
        if (convertView == null)
        {
            v = mInflater.inflate(isExpanded ? R.layout.chat_group_item : R.layout.chat_group_item, parent, false);
        }
        else
        {
            v = convertView;
        }

        final ContactSuperBean group = mGroupData.get(groupPosition);
        TextView groupNameTV = (TextView) v.findViewById(R.id.item_expandable_group);
        final ImageView openIV = (ImageView) v.findViewById(R.id.item_img_open);
        LinearLayout llGroup = (LinearLayout) v.findViewById(R.id.ll_item_group);
        groupNameTV.setText(group.getName());
        if (ContactsActivity.isClose[groupPosition] == 0)
        {
            openIV.setImageResource(R.drawable.change_store_icon);
        }
        else
        {
            openIV.setImageResource(R.drawable.change_store_icon_up);
        }
        llGroup.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v) {
                if (ContactsActivity.isClose[groupPosition] != 0)
                {
                    List<ContactBookInfo> list = mChildData.get(group.getName());
                    if (list.size() > 50)
                    {
                        List<ContactBookInfo> newList = new ArrayList<>();
                        for (int i = 0; i < 50; i++) {
                            newList.add(list.get(i));
                        }
                        mChildData.put(group.getName(), newList);
                    }
                    lvContacts.collapseGroup(groupPosition);
                    //					openIV.setBackgroundResource(R.drawable.change_store_icon);
                    openIV.setImageResource(R.drawable.change_store_icon);
                    ContactsActivity.isClose[groupPosition] = 0;
                }
                else
                {
                    for (int i = 0; i < mGroupData.size(); i++)
                    {
                        if (ContactsActivity.isClose[i] == 1)
                        {
                            List<ContactBookInfo> list = mChildData.get(mGroupData.get(i).getName());
                            if (list.size() > 50)
                            {
                                List<ContactBookInfo> newList = new ArrayList<>();
                                for (int j = 0; j < 50; j++) {
                                    newList.add(list.get(j));
                                }
                                mChildData.put(mGroupData.get(i).getName(), newList);
                            }
                            lvContacts.collapseGroup(i);
                            ContactsActivity.isClose[i] = 0;
                        }
                    }
                    lvContacts.expandGroup(groupPosition);
                    //					openIV.setBackgroundResource(R.drawable.change_store_icon_up);
                    openIV.setImageResource(R.drawable.change_store_icon_up);
                    ContactsActivity.isClose[groupPosition] = 1;
                }
            }
        });
        return v;
    }

    private class ChildViewHolder{
        private CircleImageView contactsHeadImg;
        private ImageView contactsHeader, contactsCall, contactsMsg, contactsChat;
        private TextView contactsName;
        private RelativeLayout rlItem;
    }

    @Override
    public View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        ChildViewHolder holder;
        if (convertView == null)
        {
            convertView = mInflater.inflate(isLastChild ? R.layout.chat_contact_item : R.layout.chat_contact_item, parent, false);
            holder = new ChildViewHolder();
            holder.contactsHeadImg = (CircleImageView) convertView.findViewById(R.id.iv_chat_head_img);
            holder.contactsHeader = (ImageView) convertView.findViewById(R.id.iv_chat_contact_icon_header);
            holder.contactsCall = (ImageView) convertView.findViewById(R.id.iv_chat_contact_icon_call);
            holder.contactsMsg = (ImageView) convertView.findViewById(R.id.iv_chat_contact_icon_msg);
            holder.contactsChat = (ImageView) convertView.findViewById(R.id.iv_chat_contact_icon_chat);
            holder.contactsName = (TextView) convertView.findViewById(R.id.tv_chat_contact_name);
            holder.rlItem = (RelativeLayout) convertView.findViewById(R.id.rl_contact_item);
            convertView.setTag(holder);
        }
        else
        {
            holder = (ChildViewHolder) convertView.getTag();
        }
        final ContactBookInfo contactItem = (ContactBookInfo) getChild(groupPosition, childPosition);
        holder.contactsChat.setTag(childPosition);
        if (Utils.isNotEmpty(contactItem.getUserHead()))
        {
            //			ImageUtil.loadLocalUrl(contactItem.getUserHead(), contactsHeadImg);
            Picasso.with(context).load(contactItem.getUserHead()).placeholder(R.drawable.chat_head_img).into(holder.contactsHeadImg);
        }
        else
        {
            Picasso.with(context).load(R.drawable.chat_head_img).into(holder.contactsHeadImg);
            //			contactsHeadImg.setBackgroundResource(R.drawable.chat_head_img);
        }
        if (contactItem.getGroupPosition() == 1)
        {
            Picasso.with(context).load(R.drawable.chat_contract_icon_header).into(holder.contactsHeader);
            //			contactsHeader.setBackgroundResource(R.drawable.chat_contract_icon_header);
            holder.contactsHeader.setVisibility(View.VISIBLE);
        }
        else if (contactItem.getGroupPosition() == 2)
        {
            Picasso.with(context).load(R.drawable.chat_contract_icon_deputy_header).into(holder.contactsHeader);
            //			contactsHeader.setBackgroundResource(R.drawable.chat_contract_icon_deputy_header);
            holder.contactsHeader.setVisibility(View.VISIBLE);
        }
        else
        {
            holder.contactsHeader.setVisibility(View.GONE);
        }
        holder.contactsName.setText(contactItem.getContactName());
        if (Utils.isEmpty(contactItem.getMobileNumber()))
        {
            holder.contactsMsg.setVisibility(View.GONE);
            holder.contactsChat.setVisibility(View.GONE);
        }
        else
        {
            holder.contactsMsg.setVisibility(View.VISIBLE);
            holder.contactsChat.setVisibility(View.VISIBLE);
        }
        holder.contactsMsg.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v) {
                //				NewActionHelp.qryStaffInfoByAccIds(context, contactItem.getAccId(), new NimAccountHandler(1));
                //				Utils.showToast(context, "发送短信");
                if (Utils.isNotEmpty(contactItem.getMobileNumber()))
                {
                    doSendSMSTo(contactItem.getMobileNumber(), null);
                }
            }
        });

        holder.contactsCall.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v) {
                List<String> phoneList = new ArrayList<String>();
                if (Utils.isNotEmpty(contactItem.getMobileNumber()))
                {
                    phoneList.add(contactItem.getMobileNumber());
                }
                if (Utils.isNotEmpty(contactItem.getPhoneNumber()))
                {
                    phoneList.add(contactItem.getPhoneNumber());
                }
                selectNum = new ContactCallSelectDialog(context, phoneList);
                if (phoneList.size() > 1)
                {
                    selectNum.show();
                }
                else
                {
                    dialPhoneNumber(phoneList.get(0));
                }
                //				if (Utils.isNotEmpty(contactItem.getMobileNumber()))
                //				{
                //					dialPhoneNumber(contactItem.getMobileNumber());
                //				}
                //				else if (Utils.isNotEmpty(contactItem.getPhoneNumber()))
                //				{
                //					dialPhoneNumber(contactItem.getPhoneNumber());
                //				}
            }
        });

        holder.contactsChat.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v) {
                int pos = (Integer) v.getTag();
                ContactBookInfo contactItem = (ContactBookInfo) getChild(groupPosition, pos);
                if(Const.UserStaffId.equals(contactItem.getUserId())){
                    Util.showToast(context, "您不能与自己聊天");
                    return;
                }
                ContactInfo info = new ContactInfo();
                info.setAccId(contactItem.getAccId());
                info.setAccount(contactItem.getMobileNumber());
                info.setHeadImage(contactItem.getUserHead());
                info.setStaffName(contactItem.getContactName());
                talkto(info);
            }
        });
        holder.rlItem.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, ChatPersonalInfoActivity.class);
                intent.putExtra("contactInfo", (Serializable) contactItem);
                intent.putExtra("groupName", mGroupData.get(groupPosition).getName());
                context.startActivity(intent);
            }
        });
        return convertView;
    }

    /**
     * 跳转到聊天页面
     *
     * @param item
     */
    protected void talkto(Object item) {
        if (item instanceof ContactInfo)
        {
            ContactInfo info = (ContactInfo) item;
            String str;
            if (Utils.isNotEmpty(info.getStaffName()))
            {
                str = info.getStaffName();
            }
            else if (Utils.isNotEmpty(info.getNickName()))
            {
                str = info.getNickName();
            }
            else
            {
                str = info.getAccount();
            }
            //			Intent intent = new Intent();
            //			intent.putExtra(DefaultConsts.TO_P2P_PAGE_TAG, DefaultConsts.TO_P2P_PAGE_FROM_CONTACT_MANGER);
            //			intent.putExtra(DefaultConsts.TO_P2P_PAGE_INFO, str);
            //			P2PMessageActivity.start(getActivity(), info.getAccId(), intent);
            P2PMessageActivity.start(context, info.getAccId(), str);
            //			startActivity(new Intent(getActivity(), P2PMessageActivity.class));
        }
        else if (item instanceof Team)
        {
            Team team = (Team) item;
            TeamMessageActivity.start(context, team.getId());
        }

    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    @Override
    public boolean isEmpty() {
        return mGroupData != null ? mGroupData.isEmpty() : true;
    }

    public final void load(boolean reload) {
        if (!reload && !isEmpty()) { return; }

        LogUtil.d("fw", "load");
        //		startTask(null, false);
    }

    //	public final void query(String query) {
    //		startTask(new TextQuery(query), true);
    //	}
    //
    //	public final void query(TextQuery query) {
    //		startTask(query, true);
    //	}
    //	public class NimAccountHandler
    //	        extends
    //	        ObjectHttpResponseHandler<TeamMemberX>
    //	{
    //		private int type = 1;
    //
    //		public NimAccountHandler(int type) {
    //			this.type = type;
    //		}
    //
    //		@Override
    //		public Type getType() {
    //			return new TypeToken<TeamMemberX>()
    //			{
    //			}.getType();
    //		}
    //
    //		@Override
    //		public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
    //			// TODO Auto-generated method stub
    //
    //		}
    //
    //		@Override
    //		public void onSuccess(int arg0, Header[] arg1, TeamMemberX arg2, String arg3) {
    //			if (null == arg2) return;
    //			if (type == 1)
    //			{
    //				doSendSMSTo(arg2.getAccount(), "");
    //			}
    //			else
    //			{
    //				dialPhoneNumber(arg2.getAccount());
    //			}
    //		}

    //
    //		@Override
    //		public void onSuccess(int i, Header[] headers, PersonBean personBean, String s) {
    //			if (null == personBean) return;
    //			if (type == 1)
    //			{
    //				doSendSMSTo(personBean.getmOBILE(), "");
    //			}
    //			else
    //			{
    //				dialPhoneNumber(personBean.getmOBILE());
    //			}
    //
    //		}
    //
    //		@Override
    //		public Type getType() {
    //			return new TypeToken<PersonBean>()
    //			{
    //			}.getType();
    //		}
    //	}

    /**
     * 调起系统发短信功能
     *
     * @param phoneNumber
     * @param message
     */
    public void doSendSMSTo(String phoneNumber, String message) {
        if (PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber))
        {
            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber));
            intent.putExtra("sms_body", message);
            context.startActivity(intent);
        }
    }

    /**
     * 调起系统拨号盘
     *
     * @param phoneNumber
     */
    public void dialPhoneNumber(String phoneNumber) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + phoneNumber));
        context.startActivity(intent);
    }

}
